/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.base.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.com.ksplatform.base.page.OperatorEnum;
import cn.com.ksplatform.base.page.OperatorEnum.Operator;

/**
 * ClassName:SqlRequestParamAdapter.java <br/>
 * Date: 2015年11月20日 <br/>
 * 
 * @author Mr.Xiao
 * @version 1.0
 */
@Component("paramAdapters.sqlRequestParamAdapter")
public class SqlRequestParamAdapter implements IRequestParamAdapter{

	@Override
	public Map<String, Object> doAdapter(HttpServletRequest request,
			Map<String, Class> rowMapper) throws Exception {
		StringBuffer whereSql = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		String rule = request.getParameter("rule");
		if(!StringUtils.hasText(rule)){
			throw new RuleNotFondException("请求对象未设置rule");
		}
		String[] rules = rule.split("@");
		
		for(int i=0;i<rules.length;i++){
			String[] nameAndrule = rules[i].split("[*]");
			String n = nameAndrule[0];
			Operator o = OperatorEnum.Operator.getOperatorEnum(nameAndrule[1]);
			String[] vs = request.getParameterValues(n);
			
			if(vs==null){
				//浏览器自动将数组转换为参数时会增加[]
				vs = request.getParameterValues(n+"[]");
			}
			
			if(vs!=null && vs.length > 0 && StringUtils.hasLength(vs[0])){
				String tempSql = o.mate(n, vs);
				for(String v : vs){
					params.add(v);
				}
				whereSql.append(" and ").append(tempSql);
			}
		}
		
		Map<String, Object> re = new HashMap<String, Object>();
		re.put("query", whereSql.length() >= 1 ? whereSql.substring(4) : whereSql);
		re.put("params", params);
		
		return re;
	}

}
